﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using webapi.DTO;
using webapi.Helper;
using webapi.Model;

namespace webapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    public class CartController : ControllerBase
    {
        private readonly ILogger<CartController> _logger;

        private DbContextHelper _dbContextHelper;

        public CartController(ILogger<CartController> logger, DbContextHelper dbContextHelper)
        {
            _logger = logger;
            _dbContextHelper = dbContextHelper;
        }

        /// <summary>
        /// 获取购物车过滤器
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetCartFilter")]
        [Authorize]
        public ProductsFilterOutputDTO GetCartFilter([FromBody] ProductsFilterInputDTO input)
        {
            return new ProductsFilterOutputDTO();
        }

        /// <summary>
        /// 获取购物车内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetCartInfo")]
        [Authorize]
        public GetCartOutputDTO GetCartInfo([FromBody] GetCartInputDTO input)
        {
            var user = HttpContext.User.Claims;
            var userGuid = user.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            List<CartItem> cartItems = new List<CartItem>();
            List<CartModel> cart = new List<CartModel>();
            if(!string.IsNullOrWhiteSpace(input.userGuid))
            {
                cart = _dbContextHelper.CartModel.Where(b => b.USER_GUID == userGuid).ToList();
            }
            else
            {
                return new GetCartOutputDTO() 
                {
                    error_code = "2001",
                    status = "200",
                    msg = ""
                };
            }
            foreach(var item in cart)
            {
                ProductInfoModel productInfo = _dbContextHelper.ProductInfo.Where(p => p.GUID == item.PRODUCT_INFO_GUID).FirstOrDefault();
                if (productInfo != null)
                {
                    cartItems.Add(new CartItem()
                    {
                        product_id = item.PRODUCT_ID.ToString(),
                        price = productInfo.PRODUCT_PRICE,
                        product_media1  = productInfo.PRODUCT_MEDIA1,
                        product_name = productInfo.PRODUCT_NAME,
                        quantity = item.QUANTITY,
                        product_stock = productInfo.PRODUCT_NUM
                    });
                }

            }
            return new GetCartOutputDTO() { 
                data = cartItems,
                error_code = "2000",
                status = "200",
                msg = ""
            };
        }

        [HttpPost("ChangeProductCount")]
        [Authorize]
        public OutputDTO ChangeProductCount([FromBody] ChangeCartProductCountInput input)
        {
            var user = HttpContext.User.Claims;
            var userGuid = user.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var productId = int.Parse(input.product_id);
            if (!string.IsNullOrWhiteSpace(input.product_id) && !string.IsNullOrWhiteSpace(input.quantity))
            {
                var product = _dbContextHelper.CartModel.Where(p => p.PRODUCT_ID == productId && p.USER_GUID == userGuid).FirstOrDefault();
                if (product != null)
                {
                    product.QUANTITY = input.quantity;
                    _dbContextHelper.SaveChanges();
                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Change cart info succeed."
                    };
                }
            }
            return new OutputDTO()
            {
                error_code = "2001",
                status = "200",
                msg = "Change cart info failed."
            };
        }

        [HttpPost("RemoveCartProduct")]
        [Authorize]
        public OutputDTO RemoveCartProduct([FromBody] RemoveCartProductInput input)
        {
            var user = HttpContext.User.Claims;
            var userGuid = user.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var productId = int.Parse(input.product_id);
            if (!string.IsNullOrWhiteSpace(input.product_id))
            {
                var product = _dbContextHelper.CartModel.Where(p => p.PRODUCT_ID == productId && p.USER_GUID == userGuid).FirstOrDefault();
                if (product != null)
                {
                    _dbContextHelper.CartModel.Remove(product);
                    _dbContextHelper.SaveChanges();
                    return new OutputDTO()
                    {
                        error_code = "2000",
                        status = "200",
                        msg = "Remove product succeed."
                    };
                }

            }
            return new OutputDTO()
            {
                error_code = "2001",
                status = "200",
                msg = "Remove product failed."
            };
        }

        [HttpPost("AddProductToCart")]
        [Authorize]
        public OutputDTO AddProductToCart([FromBody] AddProductToCartInput input)
        {
            var user = HttpContext.User.Claims;
            var userGuid = user.FirstOrDefault(c => c.Type == "UserGuid")?.Value;
            var productId =int.Parse(input.product_id);

            if (!string.IsNullOrWhiteSpace(input.product_id))
            {
                var productInfo = _dbContextHelper.ProductInfo.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
                var productAll = _dbContextHelper.Product.Where(p => p.PRODUCT_ID == productId).FirstOrDefault();
                var cartItem = _dbContextHelper.CartModel.Where(p => p.PRODUCT_ID == productId && p.USER_GUID == userGuid).FirstOrDefault();
                if(cartItem != null)
                {
                    return new OutputDTO()
                    {
                        error_code = "2003",
                        status = "200",
                        msg = "The product already exists in the shopping cart."
                    };
                }
                if (productInfo != null && productAll != null)
                {
                    if (int.Parse(productInfo.PRODUCT_NUM) > 0)
                    {
                        var newCartItem = new CartModel();
                        newCartItem.GUID = Guid.NewGuid().ToString();
                        newCartItem.PRODUCT_INFO_GUID = productInfo.GUID;
                        newCartItem.PRODUCT_ID = productId;
                        newCartItem.QUANTITY = input.quantity;
                        newCartItem.ADD_DATETIME = DateTime.Now;
                        newCartItem.PRODUCT_INFO_GUID = productInfo.GUID;
                        newCartItem.USER_GUID = input.user_guid;
                        newCartItem.PRODUCT_ALL_GUID = productAll.GUID;
                        _dbContextHelper.CartModel.Add(newCartItem);
                        _dbContextHelper.SaveChanges();
                        return new OutputDTO()
                        {
                            error_code = "2000",
                            status = "200",
                            msg = "Add product to cart succeed."
                        };
                    }
                    return new OutputDTO()
                    {
                        error_code = "2002",
                        status = "200",
                        msg = "Out of Stock."
                    };
                }
            }
            return new OutputDTO()
            {
                error_code = "2001",
                status = "200",
                msg = "Add product failed."
            };
        }
    }
}
